import { defineStore } from 'pinia'
import { useMessage } from "@/hooks/web/useMessage";

export interface ReportMaterial {
  id: string
  type: 'image' | 'text' | 'table' | 'chart'
  content: string // 图片为base64或URL，文本为HTML，图表为配置
  title: string
  createdAt: Date
  // 新增字段用于标识来源
  sourceId?: string // 来源ID，如预警ID
  sourceType?: string // 来源类型，如"warning"、"chart"
}

export const useReportStore = defineStore('report', {
  state: () => ({
    materials: [] as ReportMaterial[],
    activeReportId: null as number | null,
    // 新增：当前编辑的报告内容
    currentReportContent: ''
  }),

  actions: {
    // 添加素材
    addMaterial(material: Omit<ReportMaterial, 'id' | 'createdAt'>) {
      const message = useMessage()
      // 检查是否已添加相同的素材
      const exists = this.materials.some(
        item => item.sourceId === material.sourceId &&
          item.sourceType === material.sourceType
      )

      if (exists) {
        message.warning('该素材已添加到报告中')
        return null
      }

      const newMaterial: ReportMaterial = {
        ...material,
        id: Date.now().toString(),
        createdAt: new Date()
      }
      this.materials.push(newMaterial)
      message.success('已添加到报告素材')
      return newMaterial
    },

    // 移除素材
    removeMaterial(id: string) {
      this.materials = this.materials.filter(item => item.id !== id)
    },

    // 清空素材
    clearMaterials() {
      this.materials = []
    },

    // 设置当前活跃报告ID
    setActiveReportId(id: number | null) {
      this.activeReportId = id
    },

    // 更新当前报告内容
    updateReportContent(content: string) {
      this.currentReportContent = content
    },

    // 将素材转换为HTML内容
    convertMaterialsToHtml(): string {
      let html = ''
      this.materials.forEach(material => {
        html += `<div class="report-material" data-id="${material.id}" data-type="${material.type}">`
        html += `<h3>${material.title}</h3>`

        switch (material.type) {
          case 'text':
          case 'table':
            html += material.content
            break
          case 'image':
          case 'chart':
            html += `<img src="${material.content}" alt="${material.title}" style="max-width:100%;height:auto;"/>`
            break
        }
        html += `<hr/></div>`
      })
      return html
    },

    // 合并素材到报告内容
    mergeMaterialsToContent(): string {
      // 先添加已有内容
      let html = this.currentReportContent

      // 再添加所有素材
      html += this.convertMaterialsToHtml()

      return html
    }
  }
})
